package com.white.FalseWorld;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.white.FalseWorld.adapters.NineImageAdapter;
import com.white.FalseWorld.beans.pyq;
import com.white.FalseWorld.utils.GlideRoundImage;
import com.white.FalseWorld.widgets.AutoLinearLayout;
import com.white.FalseWorld.widgets.EmojiPanelView;
import com.white.FalseWorld.widgets.NineGridView;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ch.ielse.view.imagewatcher.ImageWatcher;

import static java.sql.DriverManager.getConnection;

public class GrqMainActivity extends AppCompatActivity {

    private ImageWatcher mImageWatcher;
    private EmojiPanelView mEmojiPanelView;
    private String pyq_id;

    private TextView grqmain_username,grqmain_content,grqmain_url_text,grqmain_address,grqmain_wx_day,grqmain_wx_time,grqmain_wx_delete;
    private ImageView grqmain_headpicture,grqmain_url_img,grqmain_wx_pl;
    private LinearLayout grqmain_url;
    private NineGridView grqmain_textAndimg;

    private AutoLinearLayout grqmain_like_imgs;

    GlideRoundImage glideRoundImage=new GlideRoundImage();

    private RequestOptions mRequestOptions;
    private DrawableTransitionOptions mDrawableTransitionOptions;

    private String temp_user,temp_headpicture,temp_pyq_text,temp_pyq_picture_href,temp_pyq_web_text,temp_pyq_web_picture,temp_pyq_time,temp_pyq_place;
    private int temp_pyq_type,temp_pyq_like_num,temp_pyq_day,temp_pyq_mouth,temp_pyq_year;
    ArrayList<pyq> list = new ArrayList<pyq>();
    private ImageView grqmain_img_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_grq_main );

        ImmersionBar.with(this).init();//一键透明状态栏

        pyq_id = getIntent().getStringExtra("grq_id");
        //Toast.makeText( this, pyq_id,Toast.LENGTH_SHORT).show();

        grqmain_username=findViewById( R.id.grqmain_username );
        grqmain_content=findViewById( R.id.grqmain_content );
        grqmain_url_text=findViewById( R.id.grqmain_url_text );
        grqmain_address=findViewById( R.id.grqmain_address );
        grqmain_wx_day=findViewById( R.id.grqmain_wx_day );
        grqmain_wx_time=findViewById( R.id.grqmain_wx_time );
        grqmain_wx_delete=findViewById( R.id.grqmain_wx_delete );
        grqmain_headpicture=findViewById( R.id.grqmain_headpicture );
        grqmain_url_img=findViewById( R.id.grqmain_url_img );
        grqmain_wx_pl=findViewById( R.id.grqmain_wx_pl );
        grqmain_url=findViewById( R.id.grqmain_url );
        grqmain_textAndimg=findViewById( R.id.grqmain_textAndimg );
        grqmain_img_back=findViewById( R.id.grqmain_img_back );

        grqmain_like_imgs=findViewById( R.id.grqmain_like_imgs );



        mRequestOptions = new RequestOptions().centerCrop();
        mDrawableTransitionOptions = DrawableTransitionOptions.withCrossFade();

        pyqMain_query_mysql_init();


        grqmain_img_back.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        } );
    }

    private void pyqMain_query_mysql_init() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    String[] temp_picture_string;
                    List<String> temp_picture_list = new ArrayList<>( );
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection cn= getConnection( getString( R.string.mysql_address ),getString( R.string.mysql_username ),getString( R.string.mysql_password ));
                    System.out.println("连接数据库成功");
                    String sql="SELECT * FROM personals WHERE user_id=(SELECT user_id FROM pyq WHERE pyq_id="+pyq_id+")";
                    Statement st=(Statement)cn.createStatement();
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        temp_user=rs.getString("user");
                        temp_headpicture=rs.getString( "headpicture" );
                        System.out.println( "11111名字："+temp_user+"头像地址："+temp_headpicture);
                    }
                    sql="SELECT * FROM pyq WHERE pyq_id="+pyq_id;
                    rs=st.executeQuery(sql);
                    while(rs.next()){
                        temp_pyq_type=rs.getInt("pyq_type");
                        temp_pyq_text=rs.getString( "pyq_text" )+"";
                        temp_pyq_picture_href=rs.getString( "pyq_picture_href" )+"";
                        temp_pyq_web_text=rs.getString( "pyq_web_text" )+"";
                        temp_pyq_web_picture=rs.getString( "pyq_web_picture" )+"";
                        temp_pyq_like_num=rs.getInt( "pyq_like_num" );
                        temp_pyq_day=rs.getInt( "pyq_day" );
                        temp_pyq_mouth=rs.getInt( "pyq_mouth" );
                        temp_pyq_year=rs.getInt( "pyq_year" );
                        temp_pyq_time=rs.getString( "pyq_time" )+"";
                        temp_pyq_place=rs.getString( "pyq_place" )+"";
                        if (!temp_pyq_picture_href.equals( "" )|!temp_pyq_picture_href.equals( "null" )|!temp_pyq_picture_href.equals( " " )){
                            temp_picture_string=new String[temp_pyq_picture_href.split( "," ).length];
                            for (int i=0;i<temp_pyq_picture_href.split( "," ).length;i++){
                                temp_picture_string[i]=getString( R.string.url_prefix )+temp_pyq_picture_href.split( "," )[i];
                            }
                            temp_picture_list= Arrays.asList(temp_picture_string);
                        }


                        pyq pyq=new pyq();
                        pyq.setPyq_type( temp_pyq_type );
                        pyq.setPyq_text(temp_pyq_text  );
                        pyq.setPyq_picture_href(temp_pyq_picture_href  );
                        pyq.setPyq_web_text( temp_pyq_web_text );
                        pyq.setPyq_web_picture( temp_pyq_web_picture );
                        pyq.setPyq_like_num(temp_pyq_like_num);
                        pyq.setPyq_day( temp_pyq_day );
                        pyq.setPyq_mouth( temp_pyq_mouth );
                        pyq.setPyq_year( temp_pyq_year );
                        pyq.setPyq_time( temp_pyq_time );
                        pyq.setPyq_place(temp_pyq_place);
                        list.add( pyq );
                        System.out.println("数据库操作："+temp_pyq_type);
                    }
                    cn.close();
                    st.close();
                    rs.close();
                    Message msg = new Message();
                    Bundle data = new Bundle();

                    //将获取到的String装载到msg中
                    data.putString("user", temp_user);
                    data.putString("headpicture", getString( R.string.url_prefix )+temp_headpicture);

                    ArrayList temp_list=new ArrayList(  );
                    temp_list.add( list );
                    data.putParcelableArrayList( "list",temp_list );
                    ArrayList temp_list1=new ArrayList(  );
                    temp_list1.add( temp_picture_list );
                    data.putParcelableArrayList( "picture_list",temp_list1 );
                    msg.setData(data);
                    msg.what = 1;
                    //发消息到主线程
                    handler.sendMessage(msg);

                    System.out.println("连接数据库操作执行完毕");
                    System.out.println("数据库操作执行完毕后："+temp_pyq_type);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }
    //因为mysql在新线程中运行，所以得重新回到UI线程进行组件内容的修改等操作
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

                Bundle data = msg.getData();
                ArrayList<pyq> temp_hand_list=new ArrayList<pyq>(  );
                List<String> picturelists = new ArrayList<>(  );



                String user = data.getString("user");
                String headpicture = data.getString("headpicture");
                ArrayList list = data.getParcelableArrayList("list");
                ArrayList list1 = data.getParcelableArrayList("picture_list");
                temp_hand_list= (ArrayList<pyq>) list.get(0);//强转成你自己定义的list，这样list2就是你传过来的那个list了
                picturelists=(List<String>)list1.get( 0 );
                System.out.println("UI操作："+Integer.valueOf( temp_hand_list.get( 0 ).getPyq_type() ));
                if (Integer.valueOf( temp_hand_list.get( 0 ).getPyq_type() )==1){
                    grqmain_content.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_text() ) );
                    grqmain_textAndimg.setVisibility( View.GONE );
                    grqmain_url.setVisibility( View.GONE );
                }else if (Integer.valueOf( temp_hand_list.get( 0 ).getPyq_type() )==2){
                    grqmain_url.setVisibility( View.GONE );
                    grqmain_content.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_text() ) );
//                    if (String.valueOf( temp_hand_list.get( 0 ).getPyq_picture_href()).contains( "," )){
//                        picturelists= Arrays.asList( String.valueOf( temp_hand_list.get( 0 ).getPyq_picture_href() ).split( "," ) );
//                    }else {
//                        picturelists.add(String.valueOf( temp_hand_list.get( 0 ).getPyq_picture_href())  );
//                    }
                    grqmain_textAndimg.setAdapter( new NineImageAdapter(getApplicationContext(), mRequestOptions,
                            mDrawableTransitionOptions, picturelists) );
                }else if (Integer.valueOf( temp_hand_list.get( 0 ).getPyq_type() )==3){
                    grqmain_textAndimg.setVisibility( View.GONE );
                    grqmain_content.setVisibility( View.GONE );
                    grqmain_url_text.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_web_text() ) );
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(getString( R.string.url_prefix )+String.valueOf( temp_hand_list.get( 0 ).getPyq_web_picture() ) )
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                    Drawable drawable = new BitmapDrawable(resource);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                        grqmain_url_img.setImageDrawable(drawable);
                                    }
                                }

                            });
                }else if (Integer.valueOf( temp_hand_list.get( 0 ).getPyq_type() )==4){
                    grqmain_textAndimg.setVisibility( View.GONE );
                    grqmain_content.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_text() ) );
                    grqmain_url_text.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_web_text() ) );
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(getString( R.string.url_prefix )+String.valueOf( temp_hand_list.get( 0 ).getPyq_web_picture() ) )
                            .apply( glideRoundImage.getoptions() )
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                    Drawable drawable = new BitmapDrawable(resource);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                        grqmain_url_img.setImageDrawable(drawable);
                                    }
                                }

                            });
                }

                //设置UI
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(headpicture)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                Drawable drawable = new BitmapDrawable(resource);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    grqmain_headpicture.setImageDrawable(drawable);
                                }
                            }

                        });

                grqmain_username.setText( user );
                grqmain_wx_day.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_year() )+"年"
                        +String.valueOf( temp_hand_list.get( 0 ).getPyq_mouth() )+"月"+
                        String.valueOf( temp_hand_list.get( 0 ).getPyq_day() )+"日");
                grqmain_wx_time.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_time() ) );
                if(String.valueOf( temp_hand_list.get( 0 ).getPyq_place() ).equals( "null" )|String.valueOf( temp_hand_list.get( 0 ).getPyq_place() ).equals( " " )
                |String.valueOf( temp_hand_list.get( 0 ).getPyq_place() ).equals( "" )){
                    grqmain_address.setVisibility( View.GONE );
                }else {
                    grqmain_address.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_place() ) );
                }
                for (int i=0;i<Integer.valueOf( temp_hand_list.get( 0 ).getPyq_like_num());i++ ){
                    ImageView roundedImageView=new ImageView(getApplicationContext());
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(Constants.LIKE_HEAD_IMAGE_URL[(int) (Math.random() * 300)])
                            .apply( glideRoundImage.getoptions() )
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                    Drawable drawable = new BitmapDrawable(resource);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                        roundedImageView.setImageDrawable(drawable);
                                    }
                                }

                            });

                    grqmain_like_imgs.addView( roundedImageView );
                    roundedImageView.setPadding( 0 ,5 ,15 ,0 );
                    AutoLinearLayout.LayoutParams params = (AutoLinearLayout.LayoutParams) roundedImageView
                            .getLayoutParams();
                    params.width=((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34, getResources().getDisplayMetrics()));;
                    params.height=((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34, getResources().getDisplayMetrics()));;
                    roundedImageView.setLayoutParams( params );
                }

            } else if (msg.what ==0) {
                Toast.makeText(getApplicationContext(),"请求资源不成功",Toast.LENGTH_LONG).show();
            }
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
